﻿using System;
using System.Linq;
using System.Web.Mvc;
using Umbraco.Cms.Web;
using Umbraco.Cms.Web.Context;
using Umbraco.Cms.Web.Model.BackOffice.Trees;
using Umbraco.Cms.Web.Trees;
using Umbraco.Framework;
using Umbraco.Framework.Persistence;
using Umbraco.Framework.Persistence.Model;
using Umbraco.Framework.Persistence.Model.Constants;
using WebGarden.Hive.Providers.Products.Entity;


namespace WebGarden.Trees
{
	/// <summary>
	/// Tree controller to render out products
	/// </summary>
	[Tree("E9B3E942-9A5A-415D-AFD4-29B81AC22FC5", "Products")]
	public class ProductTreeController : SupportsEditorTreeController
    {
		/// <summary>
		/// Our custom tree controller
		/// </summary>
		/// <param name="requestContext"></param>
		public ProductTreeController(IBackOfficeRequestContext requestContext)
            : base(requestContext)
        {
        }

		protected override HiveId RootNodeId
		{
			get { return FixedHiveIds.SystemRoot; }
		}

		public override Guid EditorControllerId
		{
			get { throw new NotImplementedException("I haven't gotten around to this part yet - a lesson for the reader"); }
		}

		public override string EditorControllerName
		{
			get { throw new NotImplementedException("I haven't gotten around to this part yet - a lesson for the reader"); }
		}

		/// <summary>
		/// Get all of the products from the hive and add them to the custom tree
		/// </summary>
		/// <param name="parentId"></param>
		/// <param name="queryStrings"></param>
		/// <returns></returns>
		protected override UmbracoTreeResult GetTreeData(HiveId parentId, FormCollection queryStrings)
		{
			//if its the first level
			if (parentId == RootNodeId)
			{
				var hive = BackOfficeRequestContext.Application.Hive.GetReader<IProductsStore>(
					//BUG: this check is only a work around because the way that Hive currently works cannot return the 'real' id of the entity. SD.
					(parentId == RootNodeId)
						? new Uri("products://")
						: parentId.ToUri());

				Mandate.That(hive != null, x => new NotSupportedException("Could not find a hive provider for route: " + parentId.ToString(HiveIdFormatStyle.AsUri)));

				using (var uow = hive.CreateReadonly())
				{
					// Get all products from our hive provider
					var items = uow.Repositories.GetAll<TypedEntity>().ToArray();

					// Create a tree node for each item returned from the provider, and loop over them
					foreach (var treeNode in items.Select(product =>
								(TreeNode)CreateTreeNode(
									product.Id,
									queryStrings,
									product.Attribute<string>("description"),
									Url.GetEditorUrl(EditorControllerName, product.Id, EditorControllerId))))
					{
						// Set the icon for each product
						treeNode.Icon = "tree-user";

						// Products don't have children
						treeNode.HasChildren = false;

						//add the menu items - none in this case (Readonly provider)
						//treeNode.AddEditorMenuItem<Delete>(this, "deleteUrl", "Delete");

						// Add the tree node to the collection
						NodeCollection.Add(treeNode);
					}
				}
			}
			else
			{
				throw new NotSupportedException("The products tree does not support more than 1 level");
			}

			return UmbracoTree();
		}
	}
}
